package com.yonyou.crm.bpub.approval.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.yonyou.crm.bpub.approval.entity.ApprovalUserDO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class ApprovalUserBizServiceImpl extends BaseBizServiceImpl<ApprovalUserDO> {
	
	/*
	 * 同步用户id对应的云审id
	 */
	public void synYsUserIds(List<Map<String, Object>> list) {
		Long tenantId = Long.parseLong(InvocationInfoProxy.getTenantid());
		List<Long> userIds = new ArrayList<Long>();
		for (Map<String, Object> map : list) {
			Long userId = (Long)map.get("userId");
			String ysUserId = (String)map.get("ysUserId");
			
			String oldYsUserId = getYsUserId(userId);
			
			ApprovalUserDO approvalUserDO = new ApprovalUserDO();
			approvalUserDO.setTenantId(tenantId);
			approvalUserDO.setUserId(userId);
			approvalUserDO.setYsUserId(ysUserId);
			if (oldYsUserId == null) {
				// 新增
				dao.save(approvalUserDO);
//				saveVO(approvalUserDO);
			} else if (!ysUserId.equals(oldYsUserId)) {
				// 更新
				dao.update(approvalUserDO);
//				updateVO(approvalUserDO);
			}
			userIds.add(userId);
		}
		
		// 删除云审中不存在的用户
		if (!userIds.isEmpty()) {
			batchDeleteNotIn(userIds);
		}
		
	}
	
	public String getYsUserId(Long userId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", Long.parseLong(InvocationInfoProxy.getTenantid()));
		param.put("userId", userId);
		
		Object ysUserId = dao.selectOne(ApprovalUserDO.class, "getYsUserId", param);
		if (ysUserId == null) {
			return null;
		}
		return (String)ysUserId;
	}
	
	public int batchDeleteNotIn(List<Long> userIds) {
		if (userIds == null || userIds.size() == 0) {
			return 0;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", Long.parseLong(InvocationInfoProxy.getTenantid()));
		param.put("userIds", userIds);
		
		return dao.deleteSql(ApprovalUserDO.class, "batchDeleteApprovalUser", param);
	}
}
